import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import _ from 'loadsh'
import { TitleLine, TextLine, TextCell } from '@components/ApprovePre/Approve'

export default class DocketDatetimeHistory extends Component {
  state = {
    keyTitleMap: {}
  }

  // 格式化日期
  formatDate (date, formatter = 'YYYY-MM-DD HH:mm') {
    if (date) {
      return moment(date * 1000).format(formatter)
    }
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.action || {}, 'vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  // 格式化vars中的时间
  formatVarsTime (key) {
    const { varsMap } = this.props.action
    const v = (varsMap[key] || {}).value
    if (v) {
      return this.formatDate(parseInt(v), 'YYYY-MM-DD')
    }
    return '无'
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
    }
  }

  componentDidMount () {
    this.initKeyTitleMap()
  }

  render () {
    const { keyTitleMap } = this.state
    const { action } = this.props
    return (
      <div>
        <TitleLine title={action.step_name} operator={action.operator} time={this.formatDate(action.complete_datetime)} />
        <TextLine>
          <TextCell>{keyTitleMap.docket_datetime || '立案时间'}：{this.formatVarsTime('docket_datetime')}</TextCell>
        </TextLine>
        <TextLine>
          <TextCell style={{ width: '65%' }}>备注：{action.remark || '无'}</TextCell>
        </TextLine>
        {this.props.renderDocument()}
      </div>
    )
  }
}

DocketDatetimeHistory.proptypes = {
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  action: PropTypes.object,
  renderDocument: PropTypes.func
}

DocketDatetimeHistory.defaultProps = {
  userInfo: {},
  instance: {},
  action: {},
  renderDocument: () => { }
}
